package com.admin.service.impl;

import com.admin.common.enums.EnumResult;
import com.admin.common.util.RedisUtil;
import com.admin.service.*;
import com.admin.vo.ResultVO;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.phprpc.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.*;

@Slf4j
@Service
public class CodeImageServiceImpl implements CodeImageService {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisUtil redisUtil;

    private final String codeImageRedisKey = "captcha_code:";

    @Override
    public ResultVO getCodeImage() {
        ResultVO resultVO = new ResultVO();
        try {
            String uuid = UUID.randomUUID().toString();
            String captcha = captchaProducer.createText();
            System.out.println(captcha);
            BufferedImage image = captchaProducer.createImage(captcha);
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);

            Map<String,Object> map = new HashMap<>();
            map.put("uuid", uuid);
            map.put("image", Base64.encode(os.toByteArray()));

            //设置redis
            redisUtil.set(codeImageRedisKey+uuid, captcha, 120);
            resultVO.setCode(EnumResult.SUCCESS.getCode());
            resultVO.setMsg(EnumResult.SUCCESS.getMsg());
            resultVO.setData(map);
        } catch (Exception e) {
            log.error(e.getMessage());
            resultVO.setCode(EnumResult.SYSTEM_EXCEPTION.getCode());
            resultVO.setData(EnumResult.SYSTEM_EXCEPTION.getMsg());
        }
        return resultVO;
    }

    @Override
    public boolean validateCaptcha(String code, String uuid) {
        String redisKey = codeImageRedisKey + uuid;
        String captcha = (String) redisUtil.get(redisKey);
        if (Objects.isNull(captcha)) {
            //验证码不存在或已失效
            return false;
        }
        if (!code.equalsIgnoreCase(captcha)) {
            //验证码验证错误
            return false;
        }
        redisUtil.del(redisKey);
        return true;
    }
}
